import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';

typedef HttpErrorBuilder = Widget Function(BuildContext context, String error);
typedef HttpSuccessBuilder<T> = Widget Function(BuildContext context, T data);
typedef HttpLoadingBuilder = Widget Function(BuildContext context);
typedef BlocCreator<B> = B Function(BuildContext context);

class HttpWidget<T, B extends HttpBloc<T>> extends StatelessWidget {
  final BlocCreator<B> create;
  final HttpSuccessBuilder<T> child;
  final WidgetBuilder emptyBuilder;
  final HttpErrorBuilder errorBuilder;
  final HttpLoadingBuilder loadingBuilder;

  HttpWidget({
    Key key,
    @required this.create,
    this.child,
    this.emptyBuilder,
    this.errorBuilder,
    this.loadingBuilder,
  })  : assert(create != null),
        super(key: key);

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return BlocProvider(
      create: create,
      child: BlocBuilder<B, HttpState>(
        buildWhen: (p, c) => p != c,
        builder: (context, state) => _buildByState(context, state),
      ),
    );
  }

  Widget _buildByState(BuildContext context, HttpState state) {
    if (state is HttpLoading) {
      Widget indicator = Platform.isIOS ? CupertinoActivityIndicator() : CircularProgressIndicator(backgroundColor: Colors.white, strokeWidth: 2);
      return this.loadingBuilder != null ? this.loadingBuilder(context) : Center(child: indicator);
    }
    if (state is HttpFailure) {
      if(this.errorBuilder != null){
        return this.errorBuilder(context, state.msg);
      }
      return this.errorBuilder != null
          ? this.errorBuilder(context, state.msg)
          : Container(
        color: Colors.white,
        child: Center(
          child: Text(
            state.msg,
            style: Theme.of(context).textTheme.bodyText1,
          ),
        ),
      );
    }
    if (state is HttpSuccessWithData) {
      return this.child != null ? this.child(context, state.data) : Center();
    }
    if (state is HttpSuccess) {
      return this.emptyBuilder != null
          ? this.emptyBuilder(context)
          : Center(
              child: Text(
                "${message['noData']}",
                style: Theme.of(context).textTheme.bodyText1,
              ),
            );
    }

    return Center();
  }
}
